<template>
  <div class="container">
    <div class="myMap" id="myMap" ref="mapRef">111</div>
    <div class="btn" @click="resetClick">点击</div>
    <div class="timer" @click="timeClick">时间改变</div>
  </div>
</template>

<script>
import axios from "axios";
import config from "./useMap/config/index";
import { MyMap } from "./useMap/index";
import { pmData, list, orgList, getIdByNodeId } from "./network.js";
import { Vector as VectorLayer } from "ol/layer";
import { Vector as VectorSource } from "ol/source";
import GeoJSON from "ol/format/GeoJSON";
import {
  Stroke,
  Style,
  Fill,
  Icon,
  Text,
  Circle as CircleStyle,
} from "ol/style";

export default {
  async mounted() {
    this.mapObj = new MyMap(this.$refs.mapRef, [112.575916, 31.208539], 1.5);
    this.mapInstance = this.mapObj.map;
    console.log("地图", this.mapObj);
    const data = [
      {
        id: "行政区全国",
        name: "行政区全国",
        url: config.mapWfs.chinaPolygon,
      },
      {
        id: "行政区省",
        name: "行政区省",
        url: config.mapWfs.XZQ_SHENG,
      },
      {
        id: "行政区市",
        name: "行政区市",
        url: config.mapWfs.XZQ_SHI,
      },
    ];
    for (let i = 0; i < data.length; ++i) {
      const res = await axios.get(data[i].url);
      data[i].data = res.data;
    }
    // 添加基本地图数据
    data.map((item) => this.mapObj.addBaseMap(item));
    // 获取百度地图所有路段数据
    const AllRoadData = await this.getAllRoadData();
    console.log("异常路段数据AllRoadData", AllRoadData);
    const myd = AllRoadData.filter((item) => item.nodeId.length > 6);
    console.log("异常路段数据111", myd);
    this.mapObj.addProvinceRoad(AllRoadData);
    // this.addEvent();
    // 初始化数据绘制对应路段
    const mydaya = pmData.filter((item) => item.nodeId.length > 6);
    console.log("异常路段数据222", mydaya);

    const hadValResult = [];
    list.map((listx) => {
      const listy = pmData.find((pm) => pm.nodeId.includes(listx));
      if (listy) {
        const listz = { ...listy, nodeId: listx };
        hadValResult.push(listz);
      }
    });
    console.log("hadValResult", hadValResult);
    if (hadValResult.length > 1) {
      const [rangA, rangB] = this.sortArray(hadValResult);
      const levelNodeList1 = hadValResult.filter((had) => had.flow <= rangA);
      const levelNodeList2 = hadValResult.filter(
        (had) => had.flow > rangA && had.flow <= rangB
      );
      const levelNodeList3 = hadValResult.filter((had) => had.flow > rangB);
      console.log("处理数据levelNodeList1", levelNodeList1);
      console.log("处理数据levelNodeList2", levelNodeList2);
      console.log("处理数据levelNodeList3", levelNodeList3);

      const levelNodeIDList1 = levelNodeList1.map((node) => node.nodeId);
      const levelNodeIDList2 = levelNodeList2.map((node) => node.nodeId);
      const levelNodeIDList3 = levelNodeList3.map((node) => node.nodeId);
      console.log("处理数据levelNodeIDList11", levelNodeIDList1);
      console.log("处理数据levelNodeIDList22", levelNodeIDList2);
      console.log("处理数据levelNodeIDList33", levelNodeIDList3);
      const roadList = [];
      if (levelNodeIDList1.length > 0) {
        roadList.push({
          id: "交投高速",
          name: "交投高速1",
          zIndex: 4,
          list: levelNodeIDList1,
          color: "#4FD2B1",
        });
      }
      if (levelNodeIDList2.length > 0) {
        roadList.push({
          id: "交投高速",
          name: "交投高速2",
          zIndex: 4,
          list: levelNodeIDList2,
          color: "#E4D488",
        });
      }
      if (levelNodeIDList3.length > 0) {
        roadList.push({
          id: "交投高速",
          name: "交投高速3",
          zIndex: 4,
          list: levelNodeIDList3,
          color: "#72A9E1",
        });
      }
      console.log("处理数据roadList", roadList);
      roadList.forEach((item) => {
        console.log("处理数据roadList2222", item);
        this.drawRoad(this.mapInstance, item, 0, orgList, AllRoadData);
      });
    }
  },
  methods: {
    // 请求百度地图高速公路数据
    getAllRoadData() {
      return new Promise((reslove) => {
        axios.get("/baidulevelnodesinfo.json").then((res) => {
          reslove(res.data?.result?.levelNodesInfo);
        });
      });
    },
    resetClick() {
      console.log("我被点击了");
      this.mapObj.setCenter();
    },
    timeClick() {
      console.log("我被点击了timeClick");
    },
    addEvent() {
      this.mapInstance.on("pointermove", (evt) => {
        this.showPopup(evt);
      });
      this.mapInstance.on("click", () => {
        this.closePop();
      });
    },
    showPopup: function (e) {
      console.log("地图事件pointermove", this);
      let that = this;
      let pixel = that.mapInstance.getEventPixel(e.originalEvent);
      that.mapInstance.forEachFeatureAtPixel(pixel, function (feature) {
        console.log("地图事件feature", feature);
        let params = feature.getProperties();
        console.log("地图事件params1111111111111111", params);
        if (
          params &&
          params.value &&
          params.value.type == "operationWay" &&
          params.type != "icon"
        ) {
          that.popItem = params;
          let container = document.getElementById("popup-content-sfllfx");
          that.popOverlay = new Overlay({
            element: container,
            autoPan: true,
            offset: [10, 0],
            positioning: "bottom-left",
            autoPanAnimation: {
              duration: 250,
            },
          });
          console.log("地图提示", e.coordinate, container);
          that.popOverlay.setPosition(e.coordinate);
          that.map.addOverlay(that.popOverlay);
          if (!that.popupIsEvent) {
            container.addEventListener("mouseleave", that.closePop);
            that.popupIsEvent = true;
          }
        } else {
          that.closePop();
          that.popItem = null;
        }
        return true;
      });
    },
    closePop: function () {
      console.log("地图事件click", this);
      if (this.popOverlay != null) {
        this.popOverlay.setPosition("");
        this.popOverlay = null;
      }
    },
    sortArray(sortList) {
      // 获取极差
      sortList.sort((a, b) => b.flow - a.flow);
      const min = sortList[sortList.length - 1].flow * 1;
      const max = sortList[0].flow * 1;
      const range = max - min;
      // 根据极差计算出数据范围分隔符range1,range2
      console.log("处理数据最大最小", max, min, range);
      const baseNumber1 = (range / 3 + min).toFixed() + "";

      const multiple = Math.pow(10, baseNumber1.length - 1);

      const range1 = (baseNumber1 / multiple).toFixed() * multiple;

      const baseNumber2 = ((range * 2) / 3 + min).toFixed() + "";
      const range2 = (baseNumber2 / multiple).toFixed() * multiple;
      console.log("处理数据222", range1, range2);
      return [range1, range2];
    },
    drawRoad(map, item, nodeType, orgList, roadLIst) {
      const list = item.list;

      let that = this;

      var vectorLayer = new VectorLayer({
        source: new VectorSource(),
        name: item.name,
        zIndex: item.zIndex,
      });
      var newFeatures = null;
      var arr = [];
      let gxFeatures = {
        features: [],
        type: "FeatureCollection",
      };
      let qsFeatures = {
        features: [],
        type: "FeatureCollection",
      };
      roadLIst.forEach((nodesInfo) => {
        console.log("处理数据nodesInfo", nodesInfo);
        console.log("处理数据list", list);
        console.log("处理数据orgList", orgList);
        if (list) {
          if (list.length > 0) {
            if (list.includes(nodesInfo.nodeId.toString())) {
              if (orgList && orgList.length > 0) {
                // nodeId对应上组织结构id
                arr = getIdByNodeId(orgList, nodesInfo.nodeId.toString());
              }
              JSON.parse(nodesInfo.addRoadBorder).forEach((road) => {
                console.log("处理数据road", road);
                nodesInfo.baiduNodeType = nodesInfo.nodeType;
                delete nodesInfo.nodeType;

                console.log("处理数据pmData", pmData);

                const obj = pmData.find((e) =>
                  e.nodeId.includes(nodesInfo.nodeId)
                );
                console.log("处理数据obj", obj);

                var feature = {
                  type: "Feature",
                  geometry: {
                    type: "LineString",
                    coordinates: road.path,
                  },
                  properties: {
                    id: nodesInfo.nodeId,
                    name: obj.name,
                    value: {
                      colorKey: item.color,
                      ...nodesInfo,
                      item: {
                        ...arr[0],
                      },
                      type: item.color ? "operationWay" : "highWay",
                    },
                    sfData: obj,
                  },
                };
                gxFeatures.features.push(feature);
              });
            }
          }
        } 
      });
      if (gxFeatures.features.length > 0) {
        newFeatures = new GeoJSON().readFeatures(gxFeatures);
      }
      if (qsFeatures.features.length > 0) {
        newFeatures = new GeoJSON().readFeatures(qsFeatures);
      }
      vectorLayer.getSource().clear();
      vectorLayer.setStyle(null);
      vectorLayer.getSource().addFeatures(newFeatures);
      map.addLayer(vectorLayer);

      that.getFeaturesByLayer(vectorLayer).then((features) => {
        var style = {
          strokeColor: item.color ? item.color : "rgba(255, 255, 255, 0.2)",
          strokeWidth: 3,
          fillColor: "",
          textfillColor: "#00ffaf",
          textFont: "40px",
        };
        features.forEach((feature) => {
          that.setStyleByFeature(feature, style);
        });
      });
    },
     // 获取图层的Features
    getFeaturesByLayer(layer) {
      return new Promise((resolve, reject) => {
        resolve(layer.getSource().getFeatures());
      });
    },
    addGsName(name, features) {
      this.getLayers(name, 2).then((layer) => {
        layer.setStyle(null);
        features.forEach((gs) => {
          if (gs.properties.value.item.oriWaynetId) {
            let arr = JSON.parse(gs.properties.value.addRoadBorder);
            let center = arr[0].end[0].split(",");
            gs.properties.value.id = gs.properties.value.item.id;
            gs.properties.value.longitude = center[0];
            gs.properties.value.latitude = center[1];
            this.addText(layer, gs.properties.value, "gsName");
          }
        });
      });
    },
    // 获取图层的Layers
    getLayers(name, zIndex = 10) {
      return new Promise((resolve, reject) => {
        let layer = new VectorLayer({
          source: new VectorSource({
            features: [],
          }),
          name: name,
          zIndex: zIndex,
          className:
            name && name.indexOf("高速名称") > -1
              ? "declutter-layer"
              : "ol-layer",
          declutter: name && name.indexOf("高速名称") > -1,
        });
        this.mapInstance.addLayer(layer);
        resolve(layer);
      });
    },
    // 设置WFS图层样式
    setStyleByFeature(feature, parameter) {
      let style = new Style({
        stroke: new Stroke({
          // 边线样式
          color: parameter.strokeColor ? parameter.strokeColor : "transparent",
          width: parameter.strokeWidth ? parameter.strokeWidth : 0,
          lineDash: parameter.lineDash ? parameter.lineDash : [0],
        }),
        fill: new Fill({
          // 填充样式
          color: parameter.fillColor ? parameter.fillColor : "transparent",
        }),
        image: new CircleStyle({
          // 点样式
          fill: new Fill({
            color: parameter.imagefillColor
              ? parameter.imagefillColor
              : "transparent",
          }),
          radius: parameter.imageRadius ? parameter.imageRadius : 0,
        }),
        text: new Text({
          // 文字标注样式
          font: parameter.textFont
            ? parameter.textFont
            : "0px Calibri,sans-serif",
          text: parameter.textName ? parameter.textName : "",
          fill: new Fill({
            color: parameter.textfillColor
              ? parameter.textfillColor
              : "transparent",
          }),
        }),
      });
      feature.setStyle(style);
    },
  },
};
</script>

<style scoped>
.container {
  position: relative;
  width: 100%;
  height: 100%;
  background-color: #002f50;
}
.btn {
  position: absolute;
  width: 200px;
  height: 200px;
  background-color: pink;
  top: 0;
}
.timer {
  position: absolute;
  width: 200px;
  height: 200px;
  background-color: pink;
  top: 0;
  right: 0;
}
.myMap {
  width: 100%;
  height: 100%;
}
</style>
